package com.hzl.lease.web.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.hzl.lease.common.context.LoginUserContext;
import com.hzl.lease.model.entity.BrowsingHistory;
import com.hzl.lease.web.app.mapper.BrowsingHistoryMapper;
import com.hzl.lease.web.app.service.BrowsingHistoryService;
import com.hzl.lease.web.app.vo.history.HistoryItemVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author liubo
 * @description 针对表【browsing_history(浏览历史)】的数据库操作Service实现
 * @createDate 2023-07-26 11:12:39
 */
@Service
@Slf4j
public class BrowsingHistoryServiceImpl extends ServiceImpl<BrowsingHistoryMapper, BrowsingHistory>
        implements BrowsingHistoryService {

    @Autowired
    private BrowsingHistoryMapper browsingHistoryMapper;

    @Override
    @Async  //子线程
    public void saveHistory(Long userId, Long id) {
       /* try {
            Thread.sleep(3000);
            System.out.println("保存记录。。。");
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }*/

        BrowsingHistory history = new BrowsingHistory();
        history.setUserId(userId);
        history.setRoomId(id);
        history.setBrowseTime(new Date());

        //查询用户之前是否查看过当前房间的信息.selectCount,查看总数
        Long count = browsingHistoryMapper.selectCount(new LambdaUpdateWrapper<BrowsingHistory>().eq(BrowsingHistory::getUserId, userId).eq(BrowsingHistory::getRoomId, id));
        if (count > 0) {
            //修改浏览时间
            browsingHistoryMapper.update(history,new LambdaUpdateWrapper<BrowsingHistory>().eq(BrowsingHistory::getUserId, userId).eq(BrowsingHistory::getRoomId, id));
        }else {
            //增加保存的浏览记录
            browsingHistoryMapper.insert(history);
        }


    }

    @Override
    public IPage<HistoryItemVo> pageItem(Page<Object> objectPage) {
        return browsingHistoryMapper.pageItem(objectPage , LoginUserContext.get().getUserId());
    }


}




